package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.qili.core.utils.DictTypes;
import com.qili.entity.base.BaseCompany;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.ProjectNotice;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.SupplierProjectPubNotice;
import com.qili.entity.supplier.dto.SupplierProjectAcceptDTO;
import com.qili.entity.supplier.dto.SupplierProjectDTO;
import com.qili.entity.sys.SysUser;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supplier.RecommendReasonService;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.supplier.SupplierProjectPubNoticeService;
import com.qili.util.DateUtil;
import com.qili.util.StringUtil;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyongke
 * @date 2021/4/7
 * @description 情形1、X日内无人应接：给需方发送“服务费提高”通知：您发布的XXX项目，X日内无人应接，系统建议调整服务费或招标截止时间，请确认！
 * 点击链接可以直接进入到供需详情编辑页面修改服务费和招标截止时间。
 * 其中X后台设置，X从招标截止时间往前计算，可以设置小数位数值，比如1.5日，则是招标截止时间前一天半。
 * 每次间隔 2个小时
 */

@Log
public class WbAcceptTjNoticeJob implements Job {
    @Autowired
    SysUserService sys;
    @Autowired
    private SupplierProjectPubNoticeService supplierProjectPubNoticeService;
    @Autowired
    private SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    private RecommendReasonService recommendReasonService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("JobDemo1：启动任务=======================");
        run();
        System.out.println("JobDemo1：下次执行时间=====" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime()) + "==============");
    }

    public void run() {

        log.info("WbAcceptTjNoticeJob=======开始==================================");
        String lockkey = "WbAcceptTjNoticeJob_key";
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey, uuId);
            //(2)到招标截止时间，有一人应接：则推荐此人为中标人。
            saveSendXfZbjzRiqi();

        } catch (Exception e) {
            log.info("WbAcceptTjNoticeJob=======出现异常了==================================");
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            log.info("WbAcceptTjNoticeJob=======释放锁==================================");
            unlock(lockkey, uuId);
        }
    }

    /**
     * @param
     * @Author:zhaoyongke
     * @Description: 到招标截止时间，有一人应接：则推荐此人为中标人。
     * @Date:16:09 2021/4/12
     */
    public void saveSendXfZbjzRiqi() {

        try {


            SupplierProjectDTO dtopro = new SupplierProjectDTO();
            dtopro.setStatus("006");
            dtopro.setPublishType("002");
            dtopro.setTjStatusNo("0");
            List<SupplierProjectDTO> supplierProjects = supplierProjectManagerService.selectProject(dtopro);
            System.out.println(11);

        /*    Example e = new Example(SupplierProject.class);
            Example.Criteria c = e.createCriteria();
            c.andEqualTo("status", "006");
            c.andEqualTo("publishType", "002");
            // 没有推荐过的项目
            c.andEqualTo("tjStatus", "0");
            List<SupplierProject> supplierProjects = supplierProjectManagerService.selectByExample(e);*/
            for (int i = 0; i < supplierProjects.size(); i++) {
                System.out.println(12);
                SupplierProject project = supplierProjects.get(i);
                String zbDate = project.getZbEndDate();
                Date zbEndDate = DateUtil.parseDate(zbDate, "yyyy-MM-dd HH:mm");
                Date currdate = new Date();
                if (currdate.after(zbEndDate)) {
                    System.out.println(13);
                    // 有了 综合分数才推荐
                    recommendReasonService.insertComparison(project.getSupProjectId());
                    // 到了 招标截止时间
                    SupplierProjectAcceptDTO acceptDTO = new SupplierProjectAcceptDTO();
                    acceptDTO.setSupProjectId(project.getSupProjectId());
                    acceptDTO.setScoreDesc("desc");
                    List<SupplierProjectAcceptDTO> acceptlist = supplierProjectAcceptService.selectListByScore(acceptDTO);
                    if (acceptlist.size() == 1) {
                        System.out.println(14);
                        // 有一人应接的情况
                        // 到了提醒时间 没有提醒过
                        ProjectNotice notice = new ProjectNotice();
                        notice.setLinkId(project.getSupProjectId());
                        notice.setNoticeType("105");
                        int y1 = projectNoticeServie.selectCount(notice);
                        if (y1 == 0) {
                            sendNoticeToXfTjzb(project, acceptlist.get(0));
                        }
                        project.setTjStatus("1");
                        project.setTjPerson(acceptlist.get(0).getAcceptBy());
                        project.setTjDate(DateUtil.getCurrentDateString("yyyy-MM-dd HH:mm"));
                        supplierProjectManagerService.updateByPrimaryKey(project);
                    } else if (acceptlist.size() > 1) {
                        //到招标截止时间，多人应接：系统自动推荐应接人中综合评分排行第一的为应接人。
                        String score = acceptlist.get(0).getScore();
                        System.out.println(15);
                        System.out.println(16);
                        ProjectNotice notice = new ProjectNotice();
                        notice.setLinkId(project.getSupProjectId());
                        notice.setNoticeType("105");
                        int y1 = projectNoticeServie.selectCount(notice);
                        if (y1 == 0) {
                            sendNoticeToXfTjzb(project, acceptlist.get(0));
                        }
                        project.setTjStatus("1");
                        project.setTjPerson(acceptlist.get(0).getAcceptBy());
                        project.setTjDate(DateUtil.getCurrentDateString("yyyy-MM-dd HH:mm"));
                        supplierProjectManagerService.updateByPrimaryKey(project);


                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }


    }


    /**
     * @param project
     * @Author:zhaoyongke
     * @Description:
     * @Date:15:45 2021/4/12
     */
    public void sendNoticeToXfTjzb(SupplierProject project, SupplierProjectAccept accept) {

        // 外部发布的单位 您发布的XXX项目系统推荐中标人为XXX，请在Y日内进行确
        List<BaseDict> typeListSsbl = baseDictService.selectByTypeCode(DictTypes.WXQR001.getType());
        String yvalue = "";
        if (typeListSsbl.size() > 0) {
            BaseDict bzjbl = typeListSsbl.get(0);
            yvalue = bzjbl.getBadtLevel1();
        }
        String acceptBy = accept.getAcceptBy();
        SysUser sysUser = sysUserService.selectByPrimaryKey(acceptBy);
        String personType = sysUser.getPersonType();
        String realName = "";
        if ("001".equals(personType)) {
            // 个人
            realName = sysUser.getRealName();
        } else {
            realName = sysUser.getLinkPerson();
        }
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(project.getSupProjectId());
        notice.setIsView("0");
        notice.setSendTo(project.getCreateBy());
        notice.setTitle("您发布的" + project.getProjectName() + "项目系统推荐中标人为" + realName + "，请在" + yvalue + "日内进行确认");
        notice.setNoticeType("105");// 外部单位 x天 无应接 提醒
        notice.setApplicantType("002");// 供需
        notice.setContent(project.getProjectName());
        notice.setCreateDate(DateUtil.getCurrentDateString());
        notice.setTjPerson(acceptBy);
        projectNoticeServie.insertSelective(notice);
    }



    public void lock(String key, String uuId) {
        for (; ; ) {
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            } else {
                throw new RuntimeException("已经存在的执行程序...");
            }
        }
    }

    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }

}
